package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.dtos.LikesBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.pojos.ApLikesBehavior;
import com.heima.behavior.service.LikesBehaviorService;
import com.heima.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author DiXiaoNie
 * @since 2023/1/3 15:25
 */
@Service
public class LikesBehaviorServiceImpl implements LikesBehaviorService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 点赞
     *
     * @param dto dto
     * @return {@link ResponseResult }
     * @author DiXiaoNie
     * @date 2023/01/03
     */
    @Override

    public ResponseResult like(LikesBehaviorDto dto) {

        //1.参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取用户登录ID
        ApUser apUser = ApThreadLocalUtil.getApUserThreadLocal();
        //判断是是否是游客登录
        if (apUser == null || apUser.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查看当前用户是否点赞过
        String likeKey = "USER_LIKE_" + dto.getArticleId();
        Boolean likeFlag = this.redisTemplate.opsForHash().hasKey(likeKey, apUser.getId().toString());
        // 3.1 如果点赞过，而此时的动作还是点赞行为， operation = 0 则取消返回
        if (likeFlag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(5001, "您已点赞过此作者");
        }
        // 3.2 如果没有点赞过，而此时的动作还是取消点赞行为， operation = 1 则取消返回
        if (!likeFlag && dto.getOperation() == 1) {
            return ResponseResult.errorResult(5001, "您还没有点赞过作品，请先点赞在进行此操作");
        }
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        // 3.3 如果点赞过，而此时的动作是取消点赞行为，operation = 1 则删除redis和mongo
        if (likeFlag && dto.getOperation() == 1) {
            //删除redis
            this.redisTemplate.opsForHash().delete(likeKey, apUser.getId().toString());
            //删除mongo
            this.mongoTemplate.remove(Query.query(
                    Criteria.where("userId").is(apUser.getId()).and("articleId").is(dto.getArticleId())
            ), ApFollowBehavior.class);

            updateArticleMess.setAdd(-1);
            //发送消息给kafka
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));

            return ResponseResult.okResult("取消点赞成功");
        }
        // 3.4 如果没有点赞过，而此时的动作是点赞行为，operation = 0 则新增redis和mongo
        if (!likeFlag && dto.getOperation() == 0) {
            this.redisTemplate.opsForHash().put(likeKey, apUser.getId().toString(), "1");

            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setUserId(Long.valueOf(apUser.getId()));
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setType((short) 0);
            apLikesBehavior.setCreatedTime(new Date());
            this.mongoTemplate.insert(apLikesBehavior);
        }

        updateArticleMess.setAdd(1);
        //发送消息给kafka
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult("点赞成功");
    }
}
